<?php
namespace bxd\core\plugin;

/**
 * Manager per i plugin
 *
 * @author Fabrizio Filieri
 */
class PluginManager 
{
	const PLUGIN_INI_CONFIG = "config.ini";
	
	private $activePlugins;
	
	public function __construct()
	{
		$this->activePlugins = array();
	}
	
	public function activeAllPlugin()
	{
		// Cartella base dei plugin
		$pluginBasePath = \Bxd::getInstance()->pathApplication . '/' . \Bxd::getInstance()->folderConf()->folder_plugin;
		
		// Percorso dove è presente il file di configurazione
		$configIniPath = $pluginBasePath . '/' . self::PLUGIN_INI_CONFIG;
		
		if(!file_exists($configIniPath))
			throw new exception\PluginException(\Bxd::getInstance()->folderConf()->folder_plugin, exception\PluginException::PLUGIN_NOT_FOUND);
		
		$config = parse_ini_file($configIniPath, true);
		
		foreach($config as $plugin)
		{
			$pluginConfigFile = $pluginBasePath . '/' . $plugin['package'] . '/Config.php';
			
			if(!file_exists($pluginConfigFile))
				throw new exception\PluginException($pluginConfigFile, exception\PluginException::PLUGIN_NOT_FOUND);

			include_once $pluginConfigFile;

			$className = "\\plugin\\" . $plugin['package'] . "\\Config";
			
			try
			{
				$classObject = new $className();
				
				$this->activePlugins[$className] = $classObject;
				
				/*if(!$classObject instanceof config\AbstractConfig)
					throw new exception\PluginException($pluginConfigFile, exception\PluginException::CONFIG_NOT_EXTENDS_THE_CORRECT_CLASS);				
				
				if(!$classObject instanceof config\InterfaceConfig)
					throw new exception\PluginException($pluginConfigFile, exception\PluginException::CONFIG_NOT_IMPLEMENTS_THE_CORRECT_CLASS);*/
				
				$classObject->init();
				
				$eventToLaunchTheConfig = $classObject->getEvent();
				
				if($eventToLaunchTheConfig !== null)
					\bxd\core\event\Manager::getInstance()->addCallback($eventToLaunchTheConfig, $classObject, "run");
			}
			catch(Exception $e)
			{
				throw new exception\PluginException($pluginConfigFile, exception\PluginException::INSTANCED_CLASS_ERROR);				
			}
		}
	}
	
	public function getPlugin($name)
	{
		if (isset($this->activePlugins[$name]))
			return $this->activePlugins[$name];
		
		return null;
	}
}

?>
